const http = require('http')
const https = require('https')
const url = require('url')
const qs = require('querystring')
const chalk = require('chalk')
const {createProxyMiddleware} = require('http-proxy-middleware')
const cheerio = require('cheerio')


const PORT = 8000

const api = `https://movie.douban.com/j/search_subjects?
type=movie&tag=%E7%83%AD%E9%97%A8&sort=rank&page_limit=20&page_start=10`


function get(api){
  return new Promise((resolve, reject)=>{
    let data = ''
    const request = api.startsWith('https')? https.get:http.get

    request(api, (req)=>{
      req.on('data', (chunk)=>{
        data += chunk
      })

      req.on('end', ()=>resolve(data))
    })
  })
}


function post(options){
  const {protocol} = options

  const request = protocol==='http'? http.request:https.request

  request(options, (res)=>{
    res.on('data', (chunk)=>{

    })

    res.on('end', ()=>{

    })
  })
}


function render(path){
  return new Promise((resolve, reject)=>{

  })
}

function readStaticFile(){

}


const app = http.createServer(async (req, res)=>{
  const {query} = url.parse(req.url)

  res.writeHead(200, {
    'Content-Type': 'application/json;charset=utf-8',
    'Access-Control-Allow-Origin': '*'
  })

  if(req.method==='POST'){
    let data = ''
    res.on('data', (chunk)=>{
      data += chunk
    })

    req.on('end', ()=>{
      res.end(JSON.stringify({}))
    })

    return
  }

  if(/^\/api/.test(req.url)){
    const proxy = createProxyMiddleware('/api',{
      target: '',
      changeOrigin: true,
      pathRewrite: {'^/api/':''}

    })

    proxy(req, res)

  }else {
    res.end(JSON.stringify({
      url: req.url,
      method: req.method,
      query: qs.parse(query)
    }))
  }
})


app.listen(PORT, ()=>{
  console.log(chalk.blue(`Web server is running at http://localhost:${PORT}`))
})

async function main(){
  let data = await get('https://www.mi.com/index.html')

  const $ = cheerio.load(data)

  ;[...$('[data-log_code]')].forEach((el)=>{
    console.log(el.innerHTML)
  })

}








